'use strict';
var {
    AsyncStorage,
} = require('react-native');

var KEY_USER='@message_user:user';

var cache;

/**
 * 从本地存储读取数据
 */
async function dataFromLocal(id){
    var message_user = await AsyncStorage.getItem(KEY_USER+id);
    if(message_user){
        return message_user;
    }
    return null;
}

/**
 * 从本地初始化数据
 */

async function init(id){
    cache = await dataFromLocal(id);
    return data();
}

/**
 * 返回数据
 */
function data(){
    return cache || {};
}

/**
 * 保存数据
 */
function saveMessages(messages, id){
    return AsyncStorage.setItem(KEY_USER+id, JSON.stringify(messages))
                       .then((data)=>{
                           cache=messages;
                           return cache;
                       });
}

//删除数据
function clearMessage(id){
    return AsyncStorage.removeItem(KEY_USER+id);
}

module.exports={init, data, saveMessages, clearMessage};
